package com.sharedprint.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sharedprint.system.operationlog.pojo.OperationLog;
import com.sharedprint.system.operationlog.service.OperationLogService;

public class OperationLogInterceptor implements HandlerInterceptor {
	
	@Autowired
	private OperationLogService operationLogService;
	
	private Date date = new Date();
	private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}
	/**
	 * 
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	/**
	 * 进入pageList验证token
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String token = request.getHeader("token");
		String userId = request.getHeader("userId");
		System.out.println("operationServer拦截"+"token="+token+".......userId="+userId);
		if (StringUtils.isEmpty(token) || StringUtils.isEmpty(userId)) {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("reMessage", "登陆失效！");
			String result = JSON.toJSONString(resultMap);
			response.getWriter().print(result);
			return false;
		}
		else {
			String ip = request.getLocalAddr();
			String[] urlArr = request.getRequestURL().toString().split("[/]");
			String requestUrl = request.getRequestURL().toString();
			if(urlArr[urlArr.length-1] != null && "queryPageList.action".equals(urlArr[urlArr.length-1].trim())
					|| "queryLeftMenuList.action".equals(urlArr[urlArr.length-1].trim())){
				urlArr[urlArr.length-1] = "1";
			}else{
				urlArr[urlArr.length-1] = "2";
			}
			
			OperationLog operationLog = new OperationLog();
			operationLog.setOprDate(dateFormat.format(date));
			operationLog.setIp(ip);
			operationLog.setOperatelogtype(urlArr[urlArr.length-1]);
			operationLog.setOprId(Integer.parseInt(userId));
			operationLog.setUserId(Integer.parseInt(userId));
			operationLog.setRequestUrl(requestUrl);
			operationLog.setDescription("无无无");
			int rs = operationLogService.saveInfo(operationLog);
			if(rs > 0){
				System.out.println("操作日志记录.............OperationLog.............记录完成");
			}else{
				System.out.println("操作日志记录.............OperationLog.............记录失败");
			}
			return true;
		}
	}

}
